package org.spiderflow.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

  /**
   * 获取该输入流的MD5值
   */
  public static String getMD5(InputStream is) throws NoSuchAlgorithmException, IOException {
    StringBuffer md5 = new StringBuffer();
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = is.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    }
    ;
    byte[] mdbytes = md.digest();

    // convert the byte to hex format
    for (int i = 0; i < mdbytes.length; i++) {
      md5.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
    return md5.toString();
  }

  public static void main(String[] args) {
    String path = "D:\\spider\\pdf\\RAND_CP708-2020.pdf";
    try {
      InputStream inputStream = new FileInputStream(new File(path)) ;

      String md51 = getMD5(inputStream);
      String md52 = getMD5(inputStream);
      System.out.println(md51);
      System.out.println(md52);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}